/**
 * 七牛上传
 */

import { server_request } from "../../utils/request";
import { session_storage } from "../../utils/storage";
import uploadConfig from "../../config/upload";
import * as qiniu from "qiniu-js";



function qiniuUpload( file, config){
    let qiniu_config = uploadConfig.qiniu.upload_config;
    // console.log( getSts());
    // getSts()
    session_storage( "qiniu_sts", {
        ajax_url: uploadConfig.qiniu.get_token_url,
        errorMsg: "获取七牛临时凭证失败",
        value: config.sts,
    })
        .then( ( sts) => {
            if( sts != null){
                toUpload( file,  sts, qiniu_config, config);
            }else{
                console.error( "七牛临时凭证不存在", sts);
                config.failure && config.failure( { code: 500, msg: "七牛临时凭证不存在", data: sts});
            }
        })
        .catch( (msg, res) => {
            config.failure && config.failure( { code: 500, msg: msg, data: res});
        });
}

function toUpload( file, sts, qiniu_config, config){

    try{
        let final = config.fileOnlinePath;
        if( final.substr(0,1) == "/"){
            final = final.substr(1);
        }
        let onlineFilePath = sts.host + config.fileOnlinePath;

        var observable = qiniu.upload( file, final, sts.token, {}, qiniu_config.upload_config);

        let subscription = observable.subscribe({
            next:( res)=>{
                // console.log( "subscribe next", res, onlineFilePath);
                config.progress && config.progress( { percent: res.total.percent});
            },
            error:(err) => {
                console.error( "subscribe error", err, http);
                // 参数 err 为一个包含 code、message、isRequestError 三个属性的 object
                config.failure && config.failure( { code: 500, msg: "上传失败", data: e});
            },
            complete:( res) => {
                // console.log( "subscribe complete", res, onlineFilePath);
                config.success && config.success( {
                    code: 200,
                    msg: "success",
                    data: onlineFilePath
                });
            },
        });

    }catch( e){
        config.failure && config.failure( { code: 500, msg: "上传失败", data: e});
        client.cancel();
        console.error( e);
    }
}


export default function uploadFile( file, config) {
    qiniuUpload( file, config);
}

